//
//  DataController.swift
//  SwiftIOS
//
//  Created by fearless on 2019/10/17.
//  Copyright © 2019年 fearless. All rights reserved.
//

import UIKit
import RealmSwift

class DataController: UITableViewController {
   
//    var dataModels = [
//        DataModel(name: "詹姆斯", checked: true),
//        DataModel(name: "科比", checked: false),
//        DataModel(name: "韦德", checked: false),
//        DataModel(name: "霍华德", checked: false)
//    ]
    
    var dataModels : [DataModel] = []
    
    // 设置全局变量
    var row = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 导航栏展示编辑按钮 点击触发编辑 批量选择
        navigationItem.leftBarButtonItem = editButtonItem
        editButtonItem.title = "编辑"
        // 沙盒路径
        print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))
        
        if let data = UserDefaults.standard.data(forKey: "dataModel") {
            // 解码
            do {
                dataModels = try JSONDecoder().decode([DataModel].self, from: data)
            } catch {
                print(error)
            }
        }
    }
    
    // MARK: - 批量删除数据
    @IBAction func batchDeleteData(_ sender: Any) {
        
        if let _ = tableView.indexPathsForSelectedRows {
            repeat {
                if let indexPath = tableView.indexPathForSelectedRow {
                    // 1、删除数据
                    dataModels.remove(at: indexPath.row)
                    
                    saveData()
                    // 2、更新视图
                    tableView.beginUpdates()
                    tableView.deleteRows(at: [indexPath], with: .automatic)
                    tableView.endUpdates()
                }
            } while tableView.indexPathsForSelectedRows != nil
        }

    }
    
    // 用户点击EditButton之后才会调用这个方法
    override func setEditing(_ editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)
        editButtonItem.title = isEditing ? "完成" : "编辑"
    }

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataModels.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "data", for: indexPath) as! DataCell
        cell.checkMarkLabel.text = dataModels[indexPath.row].checked ? "√" : ""
        cell.themeLabel.text = dataModels[indexPath.row].name
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if !isEditing { // 不是编辑状态下
            // 取反
            dataModels[indexPath.row].checked = !dataModels[indexPath.row].checked
            saveData()
            // 改视图
            let cell = tableView.cellForRow(at: indexPath) as! DataCell
            cell.checkMarkLabel.text = dataModels[indexPath.row].checked ? "√" : ""
            // 取消cell选中状态颜色
            tableView.deselectRow(at: indexPath, animated: true)
        }
    }
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            // 1、删除数据
            dataModels.remove(at: indexPath.row)
            // 2、更新UI
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    
    override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }

    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
        // 1、移动数据
        let dataM = dataModels[fromIndexPath.row]
        dataModels.remove(at: fromIndexPath.row)
        dataModels.insert(dataM, at: to.row)
        // 2、更新UI
//        tableView.moveRow(at: fromIndexPath, to: to)
        /// 可以直接更新
        tableView.reloadData()
    }

    // MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "addData" {
            let vc = segue.destination as! DataEditController
            vc.delegate = self
        } else if segue.identifier == "editData" {
            let vc = segue.destination as! DataEditController
            let cell = sender as! DataCell
            row = tableView.indexPath(for: cell)!.row
            vc.name = dataModels[row].name
            vc.delegate = self
        }
    }
}

extension DataController: DataDelegate {
    
    func addData(name: String) {
        // 1、添加数据
        dataModels.append(DataModel(name: name, checked: false))
        // 存储数据
        saveData()
        // 2、更新视图
        let indexPath = IndexPath(row: dataModels.count-1, section: 0)
        tableView.insertRows(at: [indexPath], with: .automatic)
    }
    
    func editData(name: String) {
        // 1、修改数据
        dataModels[row].name = name
        // 2、更新视图
        let indexPath = IndexPath(row: row, section: 0)
        // 通过indexPath找到cell
        let cell = tableView.cellForRow(at: indexPath) as! DataCell
        cell.themeLabel.text = name
    }
    
    func saveData() {
        do {
            // 编码的固定格式 --- 先创建一个编码器 (JSONEncoder() --- 然后编码(encode))
            let data = try JSONEncoder().encode(dataModels)
            UserDefaults.standard.set(data, forKey: "dataModel")
        } catch {
            print(error)
        }
    }
}
